<template>
  <div class='ele-body ele-body-card'>
    <!-- 顶部卡片 -->
    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='form'
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        @submit='checkAndPushSubmitConfig'
      >
        <a-divider orientation="left">围栏配置</a-divider>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='GEO ID:' name='geoId'>
              <a-select v-model:value="form.geoId"  @change="handleChange">
                <a-select-option :value="0">0</a-select-option>
                <a-select-option :value="1">1</a-select-option>
                <a-select-option :value="2">2</a-select-option>
                <a-select-option :value="3">3</a-select-option>
                <a-select-option :value="4">4</a-select-option>
                <a-select-option :value="5">5</a-select-option>
                <a-select-option :value="6">6</a-select-option>
                <a-select-option :value="7">7</a-select-option>
                <a-select-option :value="8">8</a-select-option>
                <a-select-option :value="9">9</a-select-option>
                <a-select-option :value="10">10</a-select-option>
                <a-select-option :value="11">11</a-select-option>
                <a-select-option :value="12">12</a-select-option>
                <a-select-option :value="13">13</a-select-option>
                <a-select-option :value="14">14</a-select-option>
                <a-select-option :value="15">15</a-select-option>
                <a-select-option :value="16">16</a-select-option>
                <a-select-option :value="17">17</a-select-option>
                <a-select-option :value="18">18</a-select-option>
                <a-select-option :value="19">19</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label="Model:" name="geoMode">
              <a-select v-model:value="form.geoMode">
                <a-select-option :value="0">Disable</a-select-option>
                <a-select-option :value="1">Entering the zone</a-select-option>
                <a-select-option :value="2">Exiting the zone</a-select-option>
                <a-select-option :value="3">Both entering and exiting</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='检查周期(秒):' name='checkInterval'>
              <a-input-number :min="0" :max="600000" v-model:value='form.checkInterval' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24' />
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Start-Eed Point:' name='startPoint'>
              Start:<a-input-number :disabled="true" :min="1" :max="10" v-model:value='form.startPoint'  allow-clear @change="startPointChange" />
              End:<a-input-number :min="3" :max="10" v-model:value='form.endPoint' allow-clear @change="endPointChange" />

              <a-button style="margin-left: 25px;" type='primary' html-type='button' @click='selectMapAction'>地图选择位置</a-button>
            </a-form-item>
          </a-col>

          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-divider orientation="left">Points Setting</a-divider>
        <a-row :gutter='8'>
          <a-col :md='24' :sm='24' :xs='24'>
            <div>
              <DeviceVehicleConfigPolygonGeofenceSubpoint v-for="(item, index) in pointObjs"
                                                          :key="index" :index="index" :point="item"

              />
            </div>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='2' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='8' :sm='24' :xs='24'>
            <a-button type='primary' html-type='submit' :loading='formSubmitLoading'>
              提交
            </a-button>
            <a-button style="margin-left: 25px;" type='primary' html-type='button' @click='readGEO' :loading='readLoading'>
              读取
            </a-button>
          </a-col>
          <a-col :md='8' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='6' :sm='24' :xs='24'></a-col>
        </a-row>
      </a-form>
    </a-card>
    <device-vehicle-config-polygon-geofence-bmap v-if="showSelectPoint" v-model:visible="showSelectPoint" :path="currentPath" @done="fillPoint" />
  </div>
</template>

<script>

import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import { message } from 'ant-design-vue';
import DeviceVehicleConfigPolygonGeofenceSubpoint from './vehicle-config-polygon-geofence-subpoint.vue'
import DeviceVehicleConfigPolygonGeofenceBmap from './vehicle-config-polygon-geofence-bmap.vue'
import {VehicleConfigPolygonGeofenceApi} from "@/api/property/vechile/VehicleConfigPolygonGeofenceApi";

export default {
  name: 'DeviceVehicleConfigPolygonGeofence',
  components: {
    DeviceVehicleConfigPolygonGeofenceSubpoint,
    DeviceVehicleConfigPolygonGeofenceBmap
  },
  props: {
    data: Object
  },
  async created() {
    this.getDetail();
  },
  data() {
    return {
      form : {},
      pointObjs : [],
      currentConfig : {},
      loading : false,

      formSubmitLoading : false,
      formSubmitTimer : undefined,

      readLoading : false,
      readTimer : undefined,
      showSelectPoint : false,
      currentPath : []
    };
  },
  methods: {
    fillPoint(path) {
      console.log("子页面回调")
      console.log(path);
      if (path && path.length > 0) {
        let points = [];
        for(let i = 0; i< path.length; i ++) {
          points.push({
            "index" : i + 1,
            "bd_latitude" : parseFloat("" + path[i].lat).toFixed(6),
            "bd_longitude" : parseFloat("" + path[i].lng).toFixed(6),
            "gcj_latitude" : "",
            "gcj_longitude" : "",
            "latitude" : "",
            "longitude" : ""
          });
        }
        this.pointObjs = points;
        this.form.startPoint = 1;
        this.form.endPoint = path.length;
      }
    },
    selectMapAction () {
      console.log(111);
      this.currentPath = JSON.parse(JSON.stringify(this.pointObjs));
      this.showSelectPoint = true;
    },
    handleChange (value) {
      this.getDetail(value);
    },
    getDetail(geoId) {
      let that = this;
      let params = {
        "recordId" : this.data.recordId,
        "geoId" : geoId || 0
      };
      VehicleConfigPolygonGeofenceApi.list(params).then(result => {
        if (result && result.length == 1) {
          that.form = result[0] || {"geoId" : params.geoId, "startPoint" : 1, "endPoint" : 3};
        } else {
          that.form = {"geoId" : params.geoId, "startPoint" : 1, "endPoint" : 3};
        }
        if (that.form.points != undefined) {
          that.pointObjs = that.form.points ? JSON.parse(that.form.points) : [];
          if (that.pointObjs.length == 0) {
            let startPoint = that.form.startPoint >= 1 ? that.form.startPoint : 1;
            let endPoint = that.form.endPoint >= 3 ? that.form.endPoint : 3;
            for (;startPoint<=endPoint;startPoint++) {
              that.pointObjs.push({
                "index" : startPoint,
                "latitude" : "",
                "longitude" : "",
                "bd_latitude" : "",
                "bd_longitude" : "",
                "gcj_latitude" : "",
                "gcj_longitude" : ""
              });
            }
          }
        } else {
          that.pointObjs = [
            {
              "index" : 1,
              "latitude" : "",
              "longitude" : "",
              "bd_latitude" : "",
              "bd_longitude" : "",
              "gcj_latitude" : "",
              "gcj_longitude" : ""
            },
            {
              "index" : 2,
              "latitude" : "",
              "longitude" : "",
              "bd_latitude" : "",
              "bd_longitude" : "",
              "gcj_latitude" : "",
              "gcj_longitude" : ""
            },
            {
              "index" : 3,
              "latitude" : "",
              "longitude" : "",
              "bd_latitude" : "",
              "bd_longitude" : "",
              "gcj_latitude" : "",
              "gcj_longitude" : ""
            }
          ];
        }
        that.currentConfig = JSON.parse(JSON.stringify(that.form));
      });
    },

    startPointChange(value) {
      if (value == undefined || value == '' || value < 1 || value > 10) {
        message.error('只能输入0-10的数字');
      } else {
        let endPoint = this.form.endPoint;
        if (value > endPoint) {
          this.form.endPoint = value;
        }
        let sourcePointObjs = [];
        this.pointObjs.forEach(function(item) {
          sourcePointObjs[item.index] = item;
        });
        let destPoints = [];
        for (let i = value;i <= this.form.endPoint;i++) {
          if (undefined != sourcePointObjs[i]) {
            destPoints.push(sourcePointObjs[i]);
          } else {
            destPoints.push({
              "index": i,
              "latitude": "",
              "longitude": "",
              "bd_latitude" : "",
              "bd_longitude" : "",
              "gcj_latitude" : "",
              "gcj_longitude" : ""
            });
          }
        }
        this.pointObjs = destPoints;
      }
    },
    endPointChange(value){
      if (value == undefined || value == '' || value < 3 || value > 10) {
        message.error('只能输入0-10的数字');
      } else {
        let startPoint = this.form.startPoint;
        if (value < startPoint) {
          this.form.startPoint = value;
        }
        let sourcePointObjs = [];
        this.pointObjs.forEach(function(item) {
          sourcePointObjs[item.index] = item;
        });
        let destPoints = [];
        for (let i = this.form.startPoint;i <= this.form.endPoint;i++) {
          if (undefined != sourcePointObjs[i]) {
            destPoints.push(sourcePointObjs[i]);
          } else {
            destPoints.push({
              "index": i,
              "latitude": "",
              "longitude": "",
              "bd_latitude" : "",
              "bd_longitude" : "",
              "gcj_latitude" : "",
              "gcj_longitude" : ""
            });
          }
        }
        this.pointObjs = destPoints;
      }
    },

    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail2(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    //-------提交
    clearSubmitConfig(){
      this.formSubmitLoading = false;
      clearInterval(this.formSubmitTimer);
    },

    checkSubmitConfig(){
      let that = this;
      this.checkProcess(6, this.clearSubmitConfig, function(){
        that.getDetail();
      });
    },

    checkAndPushSubmitConfig() {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 6
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitConfigSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitConfigSubmit() {
      this.loading = true;
      this.form.points = JSON.stringify(this.pointObjs);
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({ old: this.currentConfig, update: this.form}),
        dictate : 6, //
        sceneDictate : 6 //
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.formSubmitLoading = true; //转圈
          this.formSubmitTimer = setInterval(this.checkSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //----读取
    clearReadSubmitConfig(){
      this.readLoading = false;
      clearInterval(this.readTimer);
    },

    checkReadSubmitConfig(){
      let that = this;
      this.checkProcess(605, this.clearReadSubmitConfig, function(){
        that.getDetail();
      });
    },

    readGEO() {
      let workerDetailParams = {
        recordId: this.data.recordId,
        sceneDictate: 605
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailParams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitReadSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitReadSubmit() {
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({}),
        dictate : 605, //读取GTSPD
        sceneDictate : 605
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.readLoading = true; //转圈
          this.readTimer = setInterval(this.checkReadSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },

  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
